package net.jeeshop.web.action.manage.system;

import net.jeeshop.core.Services;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.core.system.bean.Menu;
import net.jeeshop.core.system.bean.User;
import net.jeeshop.core.util.PasswordProtection;
import net.jeeshop.services.common.Poverty;
import net.jeeshop.services.front.area.bean.Area;
import net.jeeshop.services.manage.ordership.OrdershipService;
import net.jeeshop.services.manage.system.impl.MenuService;
import net.jeeshop.services.manage.system.impl.PovertyService;
import net.jeeshop.web.action.BaseController;
import net.jeeshop.web.util.LoginUserHolder;
import net.jeeshop.web.util.RequestHolder;
import net.jeeshop.web.util.Tools;
import org.apache.commons.lang.IllegalClassException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by xvhuichuang on 2017/6/26.
 */
@Controller
@RequestMapping("/manage/poverty/")
public class PovertyAction extends BaseController<Poverty> {

    public static final String page_poverty = "/manage/povertyManage/povertyList";
    private static final String page_toAddProvertyUser = "/manage/povertyManage/editPovertyUser";
    private static final String page_toEditProvertyUser = "/manage/povertyManage/alertPovertyUser";
    private static final String page_toShowPovertyUserInfo = "/manage/povertyManage/showPovertyUserInfo";
    private static final String page_home = "/manage/system/home";

    private static final String INIT_ADDRESS = "河南省商丘市虞城县";

    @Autowired
    private PovertyService mPovertyService;
    @Autowired
    private OrdershipService mOrdershipService;
    @Autowired
    private MenuService mMenuService;

    @Override
    public Services<Poverty> getService() {
        if (mPovertyService != null){
            return mPovertyService;
        }
        return null;
    }

    //转到贫困人员页面
    @RequestMapping("toPovertyPage")
    public String toPovertyList(HttpServletRequest request, @ModelAttribute("e") Poverty e) throws Exception {
        /**
         * 由于prepare方法不具备一致性，加此代码解决init=y查询的时候条件不被清除干净的BUG
         */
        this.initPageSelect();
        setParamWhenInitQuery(e);
        int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0) offset = 0;
        e.setOffset(offset);
        PagerModel pager = mPovertyService.selectPageList(e);
        if (pager == null) {
            pager = new PagerModel();
        }
        // 计算总页数
        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)  / pager.getPageSize());
        selectListAfter(pager);
        request.setAttribute("pager", pager);
        return page_poverty;
    }

    //进入增加扶困人员页面
    @RequestMapping("toAddPovertyUser")
    public String toAddPovertyUser(HttpSession session, @ModelAttribute("e") Poverty e, ModelMap model) {
        // 获取区域列表
        putArea(model);
        model.addAttribute("e", e);
        return page_toAddProvertyUser;
    }

    //处理增加扶困人员页面逻辑
    @RequestMapping("handleAddPovertyUser")
    public String handleAddPovertyUser(HttpSession session, @ModelAttribute("e") Poverty e) {
        //组合地址
        if (e.getProvince() == null || e.getProvince().equals("")){
            e.setAddress(INIT_ADDRESS + e.getAddress());
        } else{
            e.setAddress(e.getProvince() + e.getCity() + e.getArea() + e.getAddress());
        }
        User user = LoginUserHolder.getLoginUser();
        e.setPid(user.getId());
        try {
            String personCode = "";
            while(true){
                personCode = Tools.generateNumber();
                Poverty pl = mPovertyService.selectOneByPersonCode(personCode);
                if(pl == null){
                    break;
                }
            }
            e.setPersonCode(personCode);
            mPovertyService.insert(e);
        } catch (Exception aException){
            throw new IllegalClassException("增加扶贫人员失败");
        }
        return page_home;
    }

    //处理修改用户
    @RequestMapping("doEditUser")
    public String doEditUser(HttpSession session, @ModelAttribute("e") Poverty e) throws Exception {
        try {
            mPovertyService.update(e);
        } catch (Exception aException){
            throw new IllegalClassException("修改用户失败");
        }
        return toPovertyList(RequestHolder.getRequest(), new Poverty());
    }


    @RequestMapping("toShowProvertyUser")
    public String toShowProvertyUser(HttpSession session, @ModelAttribute("e") Poverty e) {
        Poverty poverty = mPovertyService.selectOne(e);
        copyPoverty(e, poverty);
        return page_toShowPovertyUserInfo;
    }


    //进入编辑页面
    @RequestMapping("toEditProvertyUser")
    public String toEditProvertyUser(HttpSession session, @ModelAttribute("e") Poverty e, ModelMap model) {
        // 获取区域列表
        putArea(model);
        model.addAttribute("e", e);
        Poverty poverty = mPovertyService.selectOne(e);
        copyPoverty(e, poverty);
        return page_toEditProvertyUser;
    }

    //处理删除用户逻辑
    @RequestMapping("toDeleteProvertyUser")
    @ResponseBody
    public String toDeleteProvertyUser(HttpSession session, @ModelAttribute("e") Poverty e) {
        try {
            mPovertyService.delete(e);
        } catch (Exception aException){
            throw new IllegalClassException("删除用户失败");
        }
        return "";
    }

    /**
     * 分页方法
     * @return
     * @throws Exception
     */
    @RequestMapping("toPoverAlleviation_")
    public String toPoverAlleviation_(HttpServletRequest request, @ModelAttribute("e") Poverty e) throws Exception {
        /**
         * 由于prepare方法不具备一致性，加此代码解决init=y查询的时候条件不被清除干净的BUG
         */
        this.initPageSelect();
        setParamWhenInitQuery(e);
        int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0) offset = 0;
        e.setOffset(offset);
        PagerModel pager = getService().selectPageList(e);
        if (pager == null) {
            pager = new PagerModel();
        }
        // 计算总页数
        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)  / pager.getPageSize());
        selectListAfter(pager);
        request.setAttribute("pager", pager);
        return page_poverty;
    }

    private void putArea(ModelMap aModelMap){
        Map<String, Area> areaMap = SystemManager.getInstance().getAreaMap();
        aModelMap.addAttribute("provinces", areaMap.values());
    }

    private void copyPoverty(Poverty poverty, Poverty poverty_){
        poverty.setId(poverty_.getId());
        poverty.setPhone(poverty_.getPhone());
        poverty.setPid(poverty_.getPid());
        poverty.setAddress(poverty_.getAddress());
        poverty.setBankName(poverty_.getBankName());
        poverty.setBankNumber(poverty_.getBankNumber());
        poverty.setCardId(poverty_.getCardId());
        poverty.setCreateTime(poverty_.getCreateTime());
        poverty.setFamilyInfo(poverty_.getFamilyInfo());
        poverty.setGender(poverty_.getGender());
        poverty.setMoney(poverty_.getMoney());
        poverty.setName(poverty_.getName());
        poverty.setSumMoney(poverty_.getSumMoney());
        poverty.setProvince(poverty_.getProvince());
        poverty.setProvinceCode(poverty_.getProvinceCode());
        poverty.setCity(poverty_.getCity());
        poverty.setCityCode(poverty_.getCityCode());
        poverty.setArea(poverty_.getArea());
        poverty.setAreaCode(poverty_.getAreaCode());
    }

}
